package com.py.framework.common;

import java.util.ArrayList;
import java.util.List;

import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.redis.bis.JedisBisManage;

import redis.clients.jedis.Jedis;

/**
 * 单个用户登录
 * @author Leegern
 * @date   2018年4月16日
 */
public class UserSingleOnline {
	
	/**
	 * 将用户添加到在线列表   username - > jdToken
	 * @param username 用户名
	 * @param jdToken  令牌
	 * @return false 同一账号多次登录 并且踢掉最早登录账号, true 添加成功
	 */
	public static synchronized boolean putInCache(String username, String jdToken) {
		boolean result =  true;
		Jedis   jedis  =  null;
		try {
			jedis = JedisBisManage.getJedis();
			// 判断是否存在
			if (jedis.hexists(Constants.USER_SINGLE_ONLINE, username)) {
				jedis.hdel(Constants.USER_SINGLE_ONLINE, username);
				result = false;
			}
			jedis.hset(Constants.USER_SINGLE_ONLINE, username, jdToken);
		} catch (Exception e) {
			ExceptionLogger.error(e);
		} finally {
			if (null != jedis) JedisBisManage.returnResource(jedis);
		}
		return result;
	}
	
	/**
	 * 获取所有在线用户的有效令牌
	 * @return
	 */
	public static List<String> getAllUserToken() {
		List<String> tokens = new ArrayList<>();
		Jedis   jedis  =  null;
		try {
			jedis = JedisBisManage.getJedis();
			tokens = jedis.hvals(Constants.USER_SINGLE_ONLINE);
		} catch (Exception e) {
			ExceptionLogger.error(e);
		} finally {
			if (null != jedis) JedisBisManage.returnResource(jedis);
		}
		return tokens;
	}
	
	/**
	 * 清除在线用户令牌
	 * @param tokens 令牌
	 */
	public static void clearUserTokens(List<String> tokens) {
		Jedis   jedis  =  null;
		String[] tokenArray = null;
		try {
			jedis = JedisBisManage.getJedis();
			tokenArray = new String[tokens.size()];
			for (int i = 0; i < tokens.size(); i++) {
				tokenArray[i] = tokens.get(i);
			}
			jedis.hdel(Constants.USER_SINGLE_ONLINE, tokenArray);
		} catch (Exception e) {
			ExceptionLogger.error(e);
		} finally {
			if (null != jedis) JedisBisManage.returnResource(jedis);
		}
	}
}